#-*- coding: UTF-8 -*-
import hashlib
import urllib
from urllib import parse
import urllib.request
import base64
import json
import time
import requests

url_preffix='https://api.ai.qq.com/fcgi-bin/ptu/ptu_faceage'


def setParams(array, key, value):
    array[key] = value


def genSignString(parser, app_key):
    uri_str = ''
    for key in sorted(parser.keys()):
        if key == 'app_key':
            continue
        uri_str += "%s=%s&" % (key, parse.quote(str(parser[key]), safe=''))
    sign_str = uri_str + 'app_key=' + app_key

    hash_md5 = hashlib.md5(sign_str.encode('utf-8'))
    return hash_md5.hexdigest().upper()


class AiPlat(object):
    def __init__(self, app_id, app_key):
        self.app_id = app_id
        self.app_key = app_key
        self.data = {}
        self.url_data = ''

    def invoke(self, params):
        self.url_data = urllib.parse.urlencode(params).encode("utf-8")
        req = urllib.request.Request(self.url, self.url_data)
        # header = {
        #     'Content-Type': 'application/x-www-form-urlencoded',
        # }
        try:
            # data1 = requests.post(self.url, data=params, headers=header)
            # print(data1.headers)
            # str_rsp = data1.text
            rsp = urllib.request.urlopen(req)
            str_rsp = rsp.read().decode('utf-8')
            dict_rsp = json.loads(str_rsp)
            return dict_rsp
        except Exception as e:
            print(e)
            return {'ret': -1}

    def face_detectface(self, image):
        self.url = url_preffix
        setParams(self.data, 'app_id', self.app_id)
        # setParams(self.data, 'app_key', self.app_key)
        setParams(self.data, 'time_stamp', int(time.time()))
        setParams(self.data, 'nonce_str', int(time.time()))
        image_data = base64.b64encode(image)
        setParams(self.data, 'image', image_data.decode("utf-8"))
        sign_str = genSignString(self.data, self.app_key)
        setParams(self.data, 'sign', sign_str)
        return self.invoke(self.data)

